import React, {Fragment} from 'react';
import './RoleManagement.less';
import {Table, Button, Badge, Modal, Form, Input, Checkbox, Popconfirm, message} from 'antd';
import TableLayout from '../../../Layout/TableLayout';
import {queryRole, addRole, delRole, updateRole, getRoleMenu, updateMenus} from "../../../service/api";
const FormItem = Form.Item;
const CheckboxGroup = Checkbox.Group;
let columnsRoot = [
    {
        dataIndex: 'roleId',
        title: 'id',

        roleId: 'id',
        roleName: '角色名',
        remark: '备注',
        status: '状态'

    },
    {
        dataIndex: 'roleName',
        title: '角色名'
    },
    {
        dataIndex: 'remark',
        title: '备注'
    },
    {
        dataIndex: 'status',
        title: '状态'
    }
]

class AddRole extends React.Component {
    state = {
        visible: false,
        confirmLoading: false,
    }
    showModal = () => {
        this.setState({
            visible: true,
        });
    }
    handleOk = () => {
        let self = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                self.setState({
                    confirmLoading: true,
                });
                addRole(values).then(function (data) {
                    if(data.code === 200){
                        self.props.retrieve();
                        self.setState({
                            visible: false,
                            confirmLoading: false,
                        })

                    }
                })

            }
        });

    }
    handleCancel = () => {
        this.setState({
            visible: false,
        });
        this.props.form.resetFields();
    }
    render() {
        const { visible, confirmLoading } = this.state;
        const { getFieldDecorator } = this.props.form;
        return (
            <Fragment>
                <Button type="primary" onClick={this.showModal}>新增角色</Button>
                <Modal title="新增角色"
                       visible={visible}
                       maskClosable={false}
                       onOk={this.handleOk}
                       confirmLoading={confirmLoading}
                       onCancel={this.handleCancel}
                       okText="确定"
                       cancelText="取消"
                >

                    <Form className="modalForm">
                        <FormItem>
                            {getFieldDecorator('roleName', {
                                rules: [{ required: true, message: '请填写正确的用户名!',max: 12, min: 2 }],
                            })(
                                <Input placeholder="角色名(长度2-12)" />
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('remark')(
                                <Input placeholder="备注" />
                            )}
                        </FormItem>
                        <FormItem>
                            {getFieldDecorator('status', {
                                valuePropName: 'checked',
                                initialValue: true,
                            })(
                                <Checkbox>启用</Checkbox>
                            )}
                        </FormItem>
                    </Form>

                </Modal>
            </Fragment>
        );
    }
}

const AddRoleForm = Form.create()(AddRole);


class ModRole extends React.Component {
    state = {
        visible: false,
        confirmLoading: false,
        info: []
    }
    showModal = () => {
        this.setState({
            visible: true,
        });


    }

    componentWillReceiveProps(nextProps) {
        let self = this;
        if(nextProps.visible && nextProps.modId){
            self.setState({visible: nextProps.visible, info: nextProps.info, modId: nextProps.modId})
        }
    }

    handleOk = () => {
        let self = this;
        this.props.form.validateFields((err, values) => {
            if (!err) {
                self.setState({
                    confirmLoading: true,
                });
                updateRole(self.state.modId, values).then(function (data) {
                    if(data.code === 200){
                        // document.getElementById("roleName").value = "";
                        // console.log(document.getElementById("roleName"))
                        self.props.form.resetFields();
                        self.props.retrieve();
                        self.handleCancel();
                    }
                })

            }
        });
    }

    handleCancel = () => {
        this.setState({
            visible: false,
            confirmLoading: false
        });

        this.props.close();
    }

    render() {
        const { visible, confirmLoading } = this.state;
        const { getFieldDecorator } = this.props.form;

        return(
            <Modal title="修改角色"
                   visible={visible}
                   maskClosable={false}
                   onOk={this.handleOk}
                   confirmLoading={confirmLoading}
                   onCancel={this.handleCancel}
                   okText="确定"
                   cancelText="取消"
            >

                {visible && <Form className="modalForm">
                    <FormItem>
                        {getFieldDecorator('roleName', {
                            rules: [{ required: true, message: '请填写正确的用户名!',max: 12, min: 2 }],
                            initialValue: this.state.info.roleName
                        })(
                            <Input placeholder="角色名(长度2-12)" />
                        )}
                    </FormItem>
                    <FormItem>
                        {getFieldDecorator('remark',{
                            initialValue: this.state.info.remark
                        })(
                            <Input placeholder="备注" />
                        )}
                    </FormItem>
                    <FormItem>
                        {getFieldDecorator('status', {
                            valuePropName: 'checked',
                            initialValue: this.state.info.status,
                        })(
                            <Checkbox>启用</Checkbox>
                        )}
                    </FormItem>
                </Form>}

            </Modal>
        )
    }

}

const ModRoleForm = Form.create()(ModRole);

let menuType = ["目录", "菜单", "按钮"]
const columnsMenu = [
    {
        dataIndex: 'menuId',
        title: '菜单id'
    },
    {
        title: '菜单名称',
        render: (record) => (
            <div className="bold">{record.name}</div>
        )
    },
    {
        title: '上级菜单',
        render: (record) => (
            <div className="bold">{record.parentName?record.parentName:""}</div>
        )
    },
    {
        title: '菜单类型',
        render: (record) => (
            <div>{menuType[record.type]}</div>
        )
    },
]

class ModAuthority extends React.Component {

    state = {
        visible: false,
        confirmLoading: false,
        info: [],
        loading: true,
        selectedRowKeys: [],
        checkedList: [],
        authId: this.props.authId
    }

    componentWillReceiveProps(nextProps) {
        let self = this;
        if(nextProps.authId && nextProps.visible && (this.state.authId != nextProps.authId)){

            self.setState({visible: true, authId: nextProps.authId},function () {
                getRoleMenu(nextProps.authId).then(function (data) {
                    if(data.code === 200){
                        self.setState({data: data.data, loading: false})
                        let menuArr = [];

                        function traverseNode(node){
                            if(node.ifHas){
                                menuArr.push(node.menuId)
                            }

                        }

                        function traverseTree(node){
                            if (!node) {
                                return;
                            }
                            if(node.length){
                                for(let i in node){
                                    traverseNode(node[i]);
                                    if (node[i].children) {
                                        for(let x in node[i].children) {
                                            traverseTree(node[i].children[x]);
                                        }
                                    }
                                }
                            }else{
                                traverseNode(node);
                                if(node.children){
                                    for(let i in node.children){
                                        traverseNode(node.children[i])
                                    }
                                }
                            }
                        }

                        traverseTree(data.data);
                        self.setState({
                            selectedRowKeys: menuArr
                        })

                    }
                })
            })

        }
    }


    handleOk = () => {
        this.setState({confirmLoading: true});


        let self = this;
        updateMenus(this.state.authId, {menuIds :this.state.selectedRowKeys}).then(function (data) {
            if(data.code === 200){
                sessionStorage.removeItem("menu");
                message.success('修改成功');
                self.handleCancel();
                self.setState({
                    authId: ""
                })
            }
        })

    }

    handleCancel = () => {
        this.setState({
            visible: false,
            confirmLoading: false,
            info: [],
            authId: ""
        });
        this.props.close();
    }

    onSelectChange = (selectedRowKeys) => {
        // console.log('selectedRowKeys changed: ', selectedRowKeys);
        this.setState({ selectedRowKeys });
    }

    // onSelect = (record, selected, selectedRows) => {
        // console.log(record, selected, selectedRows);
    // }

    render() {
        const { visible, confirmLoading, selectedRowKeys,loading } = this.state;

        const rowSelection = {
            selectedRowKeys,
            onChange: this.onSelectChange,
        };

        return(
            <Modal title="修改角色权限"
                   visible={visible}
                   maskClosable={false}
                   onOk={this.handleOk}
                   confirmLoading={confirmLoading}
                   onCancel={this.handleCancel}
                   okText="确定"
                   cancelText="取消"
                   width="90%"
                   className="handleAuth"
            >
                <Table columns={columnsMenu} loading={loading} rowSelection={rowSelection} dataSource={this.state.data} />,
            </Modal>
        )
    }
}


class RoleManagement extends React.Component{

    constructor(props){
        super(props);
        this.getData = this.getData.bind(this);
    }

    state = {
        data: [],
        loading: true,
        permissions: JSON.parse(localStorage.permissions),
        modVisible: false,
        authVisible: false,
        modId: 0
    }

    getData(){
        let self = this;
        self.setState({loading: true})
        queryRole().then(function (data) {
            if(data.code === 200){
                self.setState({data: data.data,loading: false, modVisible:false, authVisible: false})
            }
        })
    }

    componentDidMount() {
        this.getData();
    }

    turnModalDown = () => {
        this.setState({modVisible: false, authVisible: false})
    }

    mod = (id, key) => {
        this.setState({modId :id, modVisible: true, modKey: key});
    }

    del = (id) => {
        let self = this;

        delRole(id).then(function (data) {
            if(JSON.parse(data).code === 200){
                self.getData();
            }

        })
    }

    ModAuthority = (id) => {
        this.setState({authId: id, authVisible: true})
    }

    render(){
        let data = [];
        if(this.state.data.length){
            for(let i in this.state.data){
                data.push({
                    key: i,
                    roleId: this.state.data[i].roleId,
                    roleName: this.state.data[i].roleName,
                    remark: this.state.data[i].remark,
                    status: this.state.data[i].status > 0?<Fragment><Badge status="success" />启用</Fragment>:<Fragment><Badge status="error" />停用</Fragment>
                })
            }
        }

        columnsRoot = [
            {
                dataIndex: 'roleId',
                title: 'id'
            },
            {
                dataIndex: 'roleName',
                title: '角色名'
            },
            {
                dataIndex: 'remark',
                title: '备注'
            },
            {
                dataIndex: 'status',
                title: '状态'
            },
            {
                title: '操作',
                width: 300,
                render: (record) => (
                    <div className="tableOperation">
                        {this.state.permissions["sys:role:update"]?<Button type="primary" id={record.roleId} onClick={ () => this.mod(record.roleId,record.key)}>修改</Button>:true}
                        {this.state.permissions["sys:role:toUpdateMenu"]?<Button id={record.roleId} onClick={ () => this.ModAuthority(record.roleId)}>配置权限</Button>:true}
                        {this.state.permissions["sys:role:delete"]?
                            <Popconfirm placement="leftBottom" title={`确定删除角色:${record.roleName}吗?`} id={record.roleId.toString()} onConfirm={() => this.del(record.roleId)} okText="确定" cancelText="取消">
                                <Button type="danger" id={record.roleId} ghost>删除</Button>
                            </Popconfirm>:true}
                    </div>
                )
            }
        ]

        return (
            <TableLayout title="角色管理">
                <div className="roleManagement">
                    {this.state.permissions["sys:role:add"]?<AddRoleForm retrieve={this.getData} />:true}
                    <ModRoleForm visible={this.state.modVisible} modId={this.state.modId} close={this.turnModalDown} info={this.state.data[this.state.modKey]} retrieve={this.getData} />
                    <ModAuthority visible={this.state.authVisible} authId={this.state.authId} close={this.turnModalDown} />
                    <Table className="mt10" columns={columnsRoot} dataSource={data} loading={this.state.loading} bordered />
                </div>
            </TableLayout>
        )
    }

}

export default RoleManagement;